package com.sky.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sky.properties.BaiduMapProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.util.UriUtils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@Component
public class BaiduMapUtil {
    @Autowired
    private BaiduMapProperties baiduMapProperties;

    public String URL = "https://api.map.baidu.com/geocoding/v3?";
    public String URL2 = "https://api.map.baidu.com/direction/v2/riding?";
    public boolean checkDistance(String address1,String address2) throws Exception {
        BaiduMapUtil snCal = new BaiduMapUtil();
        Map params1 = new LinkedHashMap<String, String>();
        params1.put("address", address1);
        params1.put("output", "json");
        params1.put("ak", baiduMapProperties.getAK());

        Map params2 = new LinkedHashMap<String, String>();
        params2.put("address", address2);
        params2.put("output", "json");
        params2.put("ak", baiduMapProperties.getAK());
        String coordinate1 = snCal.requestGetAK(URL, params1);
        String coordinate2 = snCal.requestGetAK(URL, params2);
        if(coordinate1!=null && coordinate2!=null){
            List lngLat1 = getLngLat(coordinate1);
            List lngLat2 = getLngLat(coordinate2);
            Map params = new LinkedHashMap<String, String>();
            params.put("origin", lngLat1.get(1)+","+lngLat1.get(0));
            params.put("destination", lngLat2.get(1)+","+lngLat2.get(0));
            params.put("ak", baiduMapProperties.getAK());
            //获取范围
            String rideJson = snCal.requestGetDis(URL2, params);
            if(rideJson != null) {
                JSONObject result = (JSONObject) JSONObject.parseObject(rideJson).get("result");
                JSONArray routes = (JSONArray) result.get("routes");
                JSONObject route = (JSONObject)routes.get(0);
                Integer distance = (Integer) route.get("distance");
                System.out.println("配送距离为："+distance);
                if(distance<5000){
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 获取经纬度
     * @param coordinate1
     */
    private List getLngLat(String coordinate1) {
        JSONObject resultJson = (JSONObject) JSONObject.parseObject(coordinate1).get("result");
        JSONObject locationJson = (JSONObject) resultJson.get("location");
        BigDecimal lng = (BigDecimal) locationJson.get("lng");
        BigDecimal lat = (BigDecimal) locationJson.get("lat");
        List<String> list = new ArrayList<>();
        list.add(lng.setScale(6, RoundingMode.HALF_UP).toString());
        list.add(lat.setScale(6, RoundingMode.HALF_UP).toString());
        System.out.println(lng+","+lat);
        return list;
    }

    /**
     * 默认ak
     * 选择了ak，使用IP白名单校验：
     * 根据您选择的AK已为您生成调用代码
     * 检测到您当前的ak设置了IP白名单校验
     * 您的IP白名单中的IP非公网IP，请设置为公网IP，否则将请求失败
     * 请在IP地址为xxxxxxx的计算发起请求，否则将请求失败
     */
    public String requestGetAK(String strUrl, Map<String, String> param) throws Exception {
        if (strUrl == null || strUrl.length() <= 0 || param == null || param.size() <= 0) {
            return null;
        }

        StringBuffer queryString = new StringBuffer();
        queryString.append(strUrl);
        for (Map.Entry<?, ?> pair : param.entrySet()) {
            queryString.append(pair.getKey() + "=");
            //    第一种方式使用的 jdk 自带的转码方式  第二种方式使用的 spring 的转码方法 两种均可
            //    queryString.append(URLEncoder.encode((String) pair.getValue(), "UTF-8").replace("+", "%20") + "&");
            queryString.append(UriUtils.encode((String) pair.getValue(), "UTF-8") + "&");
        }

        if (queryString.length() > 0) {
            queryString.deleteCharAt(queryString.length() - 1);
        }

        java.net.URL url = new URL(queryString.toString());
        System.out.println(queryString.toString());
        URLConnection httpConnection = (HttpURLConnection) url.openConnection();
        httpConnection.connect();

        InputStreamReader isr = new InputStreamReader(httpConnection.getInputStream());
        BufferedReader reader = new BufferedReader(isr);
        StringBuffer buffer = new StringBuffer();
        String line;
        while ((line = reader.readLine()) != null) {
            buffer.append(line);
        }
        reader.close();
        isr.close();
        return buffer.toString();
    }

    /**
     * 默认ak
     * 选择了ak，使用IP白名单校验：
     * 根据您选择的AK已为您生成调用代码
     * 检测到您当前的ak设置了IP白名单校验
     * 您的IP白名单中的IP非公网IP，请设置为公网IP，否则将请求失败
     * 请在IP地址为xxxxxxx的计算发起请求，否则将请求失败
     */
    public String requestGetDis(String strUrl, Map<String, String> param) throws Exception {
        if (strUrl == null || strUrl.length() <= 0 || param == null || param.size() <= 0) {
            return null;
        }

        StringBuffer queryString = new StringBuffer();
        queryString.append(strUrl);
        for (Map.Entry<?, ?> pair : param.entrySet()) {
            queryString.append(pair.getKey() + "=");
            //    第一种方式使用的 jdk 自带的转码方式  第二种方式使用的 spring 的转码方法 两种均可
            //    queryString.append(URLEncoder.encode((String) pair.getValue(), "UTF-8").replace("+", "%20") + "&");
            queryString.append(UriUtils.encode((String) pair.getValue(), "UTF-8").replace("%2C",",") + "&");
        }

        if (queryString.length() > 0) {
            queryString.deleteCharAt(queryString.length() - 1);
        }

        java.net.URL url = new URL(queryString.toString());
        System.out.println(queryString.toString());
        URLConnection httpConnection = (HttpURLConnection) url.openConnection();
        httpConnection.connect();

        InputStreamReader isr = new InputStreamReader(httpConnection.getInputStream());
        BufferedReader reader = new BufferedReader(isr);
        StringBuffer buffer = new StringBuffer();
        String line;
        while ((line = reader.readLine()) != null) {
            buffer.append(line);
        }
        reader.close();
        isr.close();
        return buffer.toString();
    }
}
